package com.colter.project.util.image;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.imageio.stream.FileImageOutputStream;

public class ImageUtil {
	private static BufferedImage loadImage(File image) {
		try {
			return ImageIO.read(image);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void addFont(String content, String sourcePath, String destPath) {
		File source = new File(sourcePath);
		BufferedImage bufferedImage = loadImage(source);

		int width = bufferedImage.getWidth();
		int height = bufferedImage.getHeight();

		Graphics graphics = bufferedImage.getGraphics();
		Font font = new Font("MicroYaHei", Font.BOLD, 30);
		graphics.setFont(font);
		graphics.setColor(Color.RED);
		graphics.drawString(content, width - (content.length() + 2) * 30, height - 30);
		FileImageOutputStream out = null;
		try {
			out = new FileImageOutputStream(new File(destPath));
			ImageIO.write(bufferedImage, destPath.substring(destPath.lastIndexOf(".") + 1), out);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.flush();
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static void addImage(String soucePath1, String soucePath2, String destPath) {
		File source1 = new File(soucePath1);
		BufferedImage b1 = loadImage(source1);
		int w1 = b1.getWidth();
		int h1 = b1.getHeight();
		File source2 = new File(soucePath2);
		BufferedImage b2 = loadImage(source2);
		int w2 = b2.getWidth();
		int h2 = b2.getHeight();

		System.out.println(w1 + " " + h1 + " " + w2 + " " + h2);
		Graphics g1 = b1.getGraphics();

		g1.drawImage(b2, w1 - w2, h1 - h2, w1, h1, 0, 0, w2, h2, null);
		FileImageOutputStream out = null;
		try {
			out = new FileImageOutputStream(new File(destPath));
			ImageIO.write(b1, destPath.substring(destPath.lastIndexOf(".") + 1), out);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.flush();
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
